package cn.dt.ymcc.mq.consumer;

import cn.dt.ymcc.domain.CourseOrder;
import cn.dt.ymcc.domain.KillCourse;
import cn.dt.ymcc.dto.KillPreOrderParamDto;
import cn.dt.ymcc.dto.PayNotifyDto;
import cn.dt.ymcc.service.ICourseOrderService;
import cn.dt.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.nio.charset.StandardCharsets;

@RocketMQMessageListener(
        consumerGroup = "order-order-consumer",
        topic = "order-delay-topic",
        selectorExpression = "order-delay--args",
        messageModel = MessageModel.BROADCASTING //发送广播模式
)
public class OrderDelayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private ICourseOrderService courseOrderService;
    @Autowired
    private RedissonClient redissonClient;
    /**
     *
     * 1.拿到以后先根据订单号查询t_pay_order中是否存在，如果存在则放置，说明已经消费
     * 2.拿不到则保存数据
     *
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        AssertUtil.isNotNull(body,"消息没有拿到");
        String orderNo = new String(body, StandardCharsets.UTF_8);
        /*
        从redis拿参数，去获取KillCourse，用killCourseId和activityId去redis拿去获取KillCourse判断是否能拿到，
        拿到了就是秒杀订单返回信号量，拿不到就是普通单取消订单即可
         */
        KillPreOrderParamDto killPreOrderParamDto = (KillPreOrderParamDto) redisTemplate.opsForValue().get(orderNo);
        AssertUtil.isNotNull(killPreOrderParamDto,"没有从redis拿到数据");
        KillCourse killCourse = killPreOrderParamDto.getKillCourse();
        Long killCourseId = killCourse.getId();
        Long activityId = killCourse.getActivityId();
        CourseOrder order = courseOrderService.selectByOrderNo(orderNo);
        Object killCoursetmp = redisTemplate.opsForHash().get("activity:" + activityId, killCourseId.toString());
        AssertUtil.isNotNull(order,"无订单存在");
        if(killCoursetmp!=null){
            //拿到了是秒杀单，走信号量库存回调流程返回秒杀的数量
            KillCourse course = (KillCourse) killCoursetmp;
            String key =activityId+":"+killCourseId;
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            semaphore.release(course.getKillCount());
        }
        order.setStatusOrder(2);//取消订单。
        courseOrderService.updateById(order);







    }
}
